//
//  NickNameTableViewController.m
//  Students affairs
//
//  Created by eliot on 16/3/8.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "NickNameTableViewController.h"

#import "SecurityUtil.h"
#import "GTMBase64.h"

@interface NickNameTableViewController ()
@property (nonatomic, strong) UITextField *textField;
@end

@implementation NickNameTableViewController

/**
 *  MARK：XIB创建
 *
 *  @return
 */

+(NickNameTableViewController*)CreatNickNameTableViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    NickNameTableViewController     *nickNameTableViewController=[story instantiateViewControllerWithIdentifier:@"NickNameTableViewController"];
    
    return nickNameTableViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"昵称";
    //设置tableView背景颜色
    self.tableView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237.2/255.0 blue:237/255.0 alpha:1];
    //设置title颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor colorWithRed:38/255.0 green:94/255.0 blue:215/255.0 alpha:1]}];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAndDismiss)];
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

//点击保存按钮
- (void)saveAndDismiss {
    NSData *getthemeAndAboutData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userModel"];
    UserModel *myUserModel = [NSKeyedUnarchiver unarchiveObjectWithData:getthemeAndAboutData];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *senddic = @{@"consumerId":[SecurityUtil encryptAESData:myUserModel.id], @"nickName":self.textField.text};
    NSString *baseUrl = [NSString stringWithFormat:@"%@saveConsumer.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:senddic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
       
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //归档
            myUserModel.nickName = self.textField.text;
            NSData *themeAndAboutData = [NSKeyedArchiver archivedDataWithRootObject:userModel];
            [[NSUserDefaults standardUserDefaults] setObject:themeAndAboutData forKey:@"userModel"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.navigationController popViewControllerAnimated:YES];

        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
   
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    self.textField = [[UITextField alloc] init];
    [cell.contentView addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.mas_equalTo(20);
       make.top.bottom.mas_equalTo(0);
       make.right.mas_equalTo(-40);
    }];
    self.textField.placeholder = @"请输入昵称";
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cell.contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(9);
        make.bottom.mas_equalTo(-9);
        make.left.mas_equalTo(self.textField.mas_right).mas_equalTo(6);
    }];
    [btn setImage:[UIImage imageNamed:@"icon_clear"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

//点击清除按钮
- (void)clearBtnClick {
    self.textField.text = @"";
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
